package com.leantech.android.browser.ui.shortcut

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.cscj.android.repository.network.Result
import com.leantech.android.browser.databinding.FragmentRecyclerViewBinding
import com.leantech.android.browser.ui.shortcut.adapter.CommentShortCut
import com.leantech.android.browser.ui.shortcut.adapter.CommonShortCutAdapter
import com.leantech.android.browser.ui.shortcut.viewmodel.ShortCutViewModel
import com.leantech.android.browser.utils.failToast
import com.leantech.android.browser.utils.successToast
import com.cscj.android.utils.LOG
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.activityViewModel

class HistoryShortCutFragment : Fragment(), CommonShortCutAdapter.CommonShortCutAdapterCallback {

    private lateinit var binding: FragmentRecyclerViewBinding

    private val viewModel by activityViewModel<ShortCutViewModel>()

    private lateinit var adapter: CommonShortCutAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = FragmentRecyclerViewBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
        collectFlow()
    }

    private fun collectFlow() {
        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                launch {
                    viewModel.historyFlow.collectLatest {
                        adapter.submitList(it)
                    }
                }
            }
        }
    }

    private fun initView() {
        adapter = CommonShortCutAdapter(this)
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
    }

    override fun addCommentShortCut(data: CommentShortCut) {
        if (data is CommentShortCut.HistoryShortCut) {
            viewLifecycleOwner.lifecycleScope.launch {
                when (val result = viewModel.addHistoryShortCut(data.item)) {
                    is Result.Success -> {
                        successToast("添加成功")
                        viewModel.refreshHistory()
                    }

                    is Result.Error -> {
                        failToast("添加失败")
                        LOG.d("error , ${result.error.errorMessage}")
                    }

                    else -> {

                    }
                }
            }
        }
    }
}